/**
 * Created by bootdo.
 */
import axios from 'axios'
import store from "../vuex/store";
import {
	bus
} from '../bus.js'

axios.defaults.withCredentials = true;
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
//  axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';//配置请求头


//添加一个请求拦截器
axios.interceptors.request.use(
	config => {
		if (window.localStorage.getItem('access-token')) {
			config.headers.Authorization = window.localStorage.getItem('access-token');
		}
		store.state.loading = true
		return config
	},
	error => {
		return Promise.reject(error)
	}
);
// 添加一个响应拦截器
axios.interceptors.response.use(function(response) {
	store.state.loading = false
	if (response.data && response.data.code) {
		if (parseInt(response.data.code) === 401) {
			//未登录
			bus.$emit('goto', '/login')
		}
	}

	return response;
}, function(error) {
	store.state.loading = false
	// Do something with response error
	return Promise.reject(error);
});

//基地址
let base = process.env.BASE_API

function request(url, method, params){
	switch (method) {
		case 'post':
			return axios.post(`${base}${url}`, params).then(res => res.data)
		case 'get':
			return axios.get(`${base}${url}`, {params: params}).then(res => res.data)
		case 'put':
			return axios.put(`${base}${url}`, params).then(res => res.data)
		case 'delete':
			return axios.delete(`${base}${url}`, {params: params}).then(res => res.data)
		case 'patch':
			return axios.patch(`${base}${url}`, params).then(res => res.data)
	}
}

//通用方法
export const POST = (url, params) => {
	return request(url,'post',params)
}

export const GET = (url, params) => {
	return request(url,'get',params)
}

export const PUT = (url, params) => {
	return request(url,'put',params)
}

export const DELETE = (url, params) => {
	return request(url,'delete',params)
}

export const PATCH = (url, params) => {
	return request(url,'patch',params)
}

export const REQUEST = (obj) => {
	return request(obj.url,obj.method,obj.params)
}
